<!--
 * 机器人管理
 -->
<template>
  <section class="robot-manage-main">
    <el-collapse-transition>
      <div v-show="searchshow" class="main-search merge">
        <span class="svg-container">
          <svg-icon icon-class="search" />
        </span>
        <el-input
          v-model.trim="listQuery.robotName"
          placeholder="请输入机器人名称搜索"
          class="search-input"
        />
        <div class="search-btn">
          <el-button
            class="filter-item"
            type="primary"
            @click="handleFilter"
          >搜索</el-button>
          <el-button
            class="filter-item"
            type="primary"
            @click="handleReset"
          >重置</el-button>
          <!--          <span class="search-more" @click="searchshow = !searchshow">-->
          <!--            更多筛选条件-->
          <!--            <i class="el-icon-arrow-down" />-->
          <!--          </span>-->
        </div>
      </div>
    </el-collapse-transition>

    <el-collapse-transition>
      <div v-show="!searchshow" class="main-search separate">
        <div class="search-inner">
          <el-row>
            <el-col :span="12">
              <div class="search-inner-item">
                <div class="item-label">用户名</div>
                <el-input
                  v-model.trim="search.robotName"
                  style="width: 80%"
                  class="filter-item"
                  placeholder="请输入用户名搜索"
                />
              </div>
            </el-col>
            <el-col :span="12">
              <div class="search-inner-item">
                <div class="item-label">闯关名称</div>
                <el-input
                  v-model.trim="search.gateName"
                  style="width: 80%"
                  class="filter-item"
                  placeholder="请输入闯关名称搜索"
                />
              </div>
            </el-col>
          </el-row>
        </div>
        <div class="search-btn">
          <el-button
            class="filter-item"
            type="primary"
            @click="handleFilter"
          >搜索</el-button>
          <el-button
            class="filter-item"
            type="primary"
            @click="handleReset"
          >重置</el-button>
          <span class="search-more" @click="searchshow = !searchshow">
            精简筛选条件
            <i class="el-icon-arrow-up" />
          </span>
        </div>
      </div>
    </el-collapse-transition>

    <section class="main-buttons">
      <section class="main-buttons-title">
        <span>机器人管理</span>
      </section>
      <section class="main-buttons-btns">
        <el-button @click="handelCreate">新增</el-button>
        <el-button
          style="margin-bottom:5px;"
          @click="handleDownload"
        >下载模板</el-button>
        <el-button @click="uploadVisible = true">批量导入</el-button>
        <el-button @click="$router.back()">返回</el-button>
      </section>
    </section>

    <section class="main-table">
      <v-table
        :list="list"
        tag="robotList"
        :list-loading="listLoading"
        :filter-column="filtercolumn"
        :selection="false"
      >
        <el-table-column
          label="操作"
          fixed="right"
          align="center"
          min-width="120"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button
              type="text"
              size="mini"
              @click="handleChangeStatus(scope.row)"
            >{{ scope.row.status === 'ZT01' ? '禁用' : '启用' }}
            </el-button>
            <el-button
              type="text"
              size="mini"
              @click="handelUpdate(scope.row)"
            >编辑</el-button>
            <el-button
              type="text"
              size="mini"
              @click="handleDelete(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </v-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.limit"
        @pagination="getList"
      />
    </section>
    <el-dialog
      :close-on-click-modal="false"
      :title="'批量导入'"
      :visible.sync="uploadVisible"
      center
      width="450px"
    >
      <el-upload
        v-if="uploadVisible"
        ref="upload"
        v-loading="loadingUpload"
        element-loading-text="正在导入请稍后"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)"
        :auto-upload="false"
        :on-success="uploadSuccess"
        :on-error="uploadError"
        :action="uploadaction"
        :headers="uploadHeaders"
        accept=".xls, .xlsx"
        class="upload-model"
        :data="uploadData"
        drag
        multiple
      >
        <i class="el-icon-upload" />
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击导入</em>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button
          style="padding: 8px 30px;"
          @click="uploadVisible = false"
        >取消</el-button>
        <el-button
          style="padding: 8px 30px;"
          type="primary"
          @click="uploadSubmit"
        >确定</el-button>
      </div>
    </el-dialog>
  </section>
</template>
<script>
import VTable from '@/components/Table'
import Pagination from '@/components/Pagination'
import { queryPage, deleteById, changeStatus, downloadTemplate } from '../api'
import { getToken } from '@/utils/auth'
import { exportSign, importSign } from '@/utils/fileImportOrExportSign'
export default {
  name: 'RobotList',
  components: { Pagination, VTable },
  data() {
    return {
      searchshow: true,
      listQuery: {
        page: 1,
        limit: 10,
        robotName: ''
      },
      search: {
        robotName: '',
        gateName: ''
      },
      list: [{}],
      total: 0,
      listLoading: false,
      fkInfoId: 'f8639d4eda0e4914999bf1078d9231d1',
      uploadVisible: false,
      loadingUpload: false,
      uploadaction: '/API-ENTERPRISE-BACKEND/backend/pkRobot/importPkRobot',
      uploadHeaders: {
        ttsxyhcs: getToken(),
        ttsxbid: 1
      },
      uploadData: {
        fkInfoId: ''
      }
    }
  },
  created() {
    this.fkInfoId = this.$route.query.fkInfoId
    this.getList()
  },
  methods: {
    filtercolumn(scope, item) {
      if (item === 'speeds') {
        return `${scope.row['speedStart'] || ''}${
          scope.row['speedStart'] && scope.row['speedEnd'] ? '-' : ''
        }${scope.row['speedEnd'] || ''}`
      } else {
        return scope.row[item]
      }
    },

    handleReset() {
      this.listQuery.page = 1
      this.listQuery.robotName = ''
      for (const i in this.search) {
        if (this.search['' + i + ''] instanceof Array) {
          this.search['' + i + ''] = []
        } else {
          this.search['' + i + ''] = ''
        }
      }
      this.getList()
    },

    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },

    getList(obj) {
      this.listLoading = true
      var query = {
        page: obj ? obj.page : this.listQuery.page,
        pageSize: obj ? obj.limit : this.listQuery.limit,
        fkInfoId: this.fkInfoId
      }
      if (this.searchshow) {
        query['robotName'] = this.listQuery.robotName
      } else {
        query['robotName'] = this.search.robotName
        query['quizName'] = this.search.gateName
      }
      return new Promise((resolve, reject) => {
        queryPage(query)
          .then((response) => {
            this.list = response.data.data.rows
            this.total = response.data.data.total
            this.listLoading = false
          })
          .catch((error) => {
            reject(error)
            this.listLoading = false
          })
      })
    },
    handleChangeStatus(row) {
      const status = row.status === 'ZT01' ? 'ZT02' : 'ZT01'
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      changeStatus({ status, id: row.id })
        .then((res) => {
          loading.close()
          this.getList()
        })
        .catch((err) => {
          loading.close(err)
        })
    },
    handelUpdate(row) {
      this.$router.push({
        path: this.$filterPath('robotManage'),
        query: {
          fkInfoId: this.fkInfoId,
          type: 'u',
          i: row.id
        }
      })
    },
    handleDelete(row) {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      deleteById({ id: row.id })
        .then((res) => {
          loading.close()
          this.getList()
        })
        .catch((err) => {
          loading.close(err)
        })
    },
    handelCreate() {
      this.$router.push({
        path: this.$filterPath('robotManage'),
        query: {
          fkInfoId: this.fkInfoId
        }
      })
    },
    uploadSuccess(data) {
      this.loadingUpload = false
      if (data.code === '200') {
        this.$message.success(data.data)
        this.getList()
        this.uploadVisible = false
      } else {
        this.$refs.upload.clearFiles()
        if (data.data && data.data.fileid) {
          setTimeout(() => {
            const link = document.createElement('a')
            link.style.display = 'none'
            link.href =
              '/API-ENTERPRISE-BACKEND/backend/liveActivityRange/downloadCheckFile?errorId=' +
              data.data.fileid
            link.setAttribute('download', '错误信息.xls')
            link.setAttribute('target', '_blank')
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)
          }, 1000)
        } else if (data.msg) {
          this.$message.error(data.msg || '批量导入失败')
        }
        this.getList()
      }
    },
    uploadError(err) {
      this.loadingUpload = false
      this.$message.error(err || '网络异常')
      this.$refs.upload.clearFiles()
    },
    uploadSubmit() {
      if (this.$refs['upload'].uploadFiles.length === 0) {
        this.$message.error('请上传文件')
      } else {
        this.uploadData.fkInfoId = this.fkInfoId
        this.$set(
          this,
          'uploadHeaders',
          importSign(this.uploadHeaders, this.uploadData)
        )
        this.$refs.upload.submit()
        this.loadingUpload = true
      }
    },
    handleDownload() {
      // return new Promise((resolve, reject) => {
      //   downloadTemplate(exportSign().paramStr)
      //     .then((response) => {
      //       // this.list = response.data.data.rows
      //       // this.total = response.data.data.total
      //       // this.listLoading = false
      //       console.log(response)
      //       const blob = new Blob([response.data])
      //       // 获取heads中的filename文件名
      //       const downloadElement = document.createElement('a')
      //       // 创建下载的链接
      //       const href = window.URL.createObjectURL(blob)
      //       downloadElement.href = href
      //       // 下载后文件名
      //       downloadElement.download = '机器人导入模板.xls'
      //       document.body.appendChild(downloadElement)
      //       // 点击下载
      //       downloadElement.click() // 下载完成移除元素
      //       document.body.removeChild(downloadElement)
      //       // 释放掉blob对象
      //     })
      //     .catch((error) => {
      //       reject(error)
      //       // this.listLoading = false
      //     })
      // })
      if (document.getElementById('downloadLinkFile')) {
        const dom = document.getElementById('downloadLinkFile')
        document.body.removeChild(dom)
      }
      const link = document.createElement('a')
      link.setAttribute('id', 'downloadLinkFile')
      link.style.display = 'none'
      link.href = '/API-ENTERPRISE-BACKEND/backend/pkRobot/downloadTemplate' + exportSign().paramStr
      link.setAttribute('download', '机器人导入模板.xls')
      link.setAttribute('target', '_blank')
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    }
  }
}
</script>
<style lang="scss">
.robot-manage-main {
  padding: 10px;
  .main-search {
    background-color: #fff;
    padding: 0 10px;
    .svg-container {
      padding: 0 5px 0 10px;
      color: #bfced6;
      vertical-align: middle;
      display: inline-block;
    }
    .search-input {
      width: 60%;
      position: relative;
      &:after {
        content: '';
        position: absolute;
        left: -25px;
        right: 0;
        bottom: 8px;
        height: 1px;
        background: rgba(226, 227, 232, 1);
      }
      input {
        outline: none;
        background: transparent;
        border: none;
        outline: medium;
        padding: 0;
        &:focus {
          outline: none;
          background-color: transparent;
        }
      }
    }
    .search-btn {
      display: inline-block;
      float: right;
      .el-button.is-round {
        padding: 10px 30px;
        margin-right: 34px;
      }
      .search-more {
        font-size: 14px;
        font-weight: 500;
        @include font-color($mainColor);
        cursor: pointer;
        margin-left: 10px;
      }
    }

    &.merge {
      height: 50px;
      line-height: 50px;
    }

    &.separate {
      .search-inner {
        padding-top: 10px;
        .search-inner-item {
          .item-label {
            height: 30px;
            line-height: 30px;
            font-size: 14px;
            color: #a6a6a6;
            font-weight: 400;
          }
          .el-input {
            position: relative;
            &.el-date-editor input {
              padding-left: 30px;
            }
            .el-input__inner {
              border: none;
              padding: 0;
            }
            &:after {
              content: '';
              height: 1px;
              background-color: #e2e3e8;
              position: absolute;
              left: 0;
              right: 0;
              bottom: 0;
            }
          }
        }
      }
      .search-btn {
        text-align: center;
        display: block;
        float: none;
        height: 56px;
        line-height: 56px;
      }
    }
  }

  .main-buttons {
    display: flex;
    line-height: 36px;
    margin-top: 10px;
    .main-buttons-title {
      flex: 1;
      height: 36px;
      line-height: 36px;
      font-size: 16px;
      font-weight: bold;
      color: rgba(51, 51, 51, 1);
    }
  }
  .upload-model {
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
  }
}
</style>
